package com.gitee.xmhzzz.rocketmq.quick;

import com.gitee.xmhzzz.rocketmq.quick.producer.DefaultMqProvider;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.apache.rocketmq.client.apis.producer.SendReceipt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RocketmqQuickApplication {

    private static final Logger logger = LoggerFactory.getLogger(RocketmqQuickApplication.class);


    public static void main(String[] args) throws InterruptedException {
        String topic = "no-spring-topic";

        DefaultMqProvider defaultMqProvider = new DefaultMqProvider();

        ExecutorService executorService = Executors.newFixedThreadPool(5);

        executorService.submit(() -> {
            defaultMqProvider.createPushConsumer("no-spring-test", topic, messageView -> {
                //处理消息并返回消费结果。
                logger.info("Consume message={}", messageView);
                return ConsumeResult.SUCCESS;
            });


        });

        Thread.sleep(12000L);
        logger.info("----------------- 创建生产者 ---------------------------");
        Producer producer = defaultMqProvider.createProducer(topic);
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        Message message = provider.newMessageBuilder()
                .setTopic(topic)
                //设置消息索引键，可根据关键字精确查找某条消息。
                .setKeys("messageKey")
                //设置消息Tag，用于消费端根据指定Tag过滤消息。
                .setTag("messageTag")
                //消息体。
                .setBody("messageBody".getBytes())
                .build();
        try {
            //发送消息，需要关注发送结果，并捕获失败等异常。
            SendReceipt sendReceipt = producer.send(message);
            System.out.println(sendReceipt.getMessageId());
        } catch (ClientException e) {
            logger.error("创建生产者失败 topic[{}] msg[{}]",topic,e.getMessage(),e);
        }


    }

}